package leetcode.code0820;

import leetcode.IDebug;

public class Solution implements IDebug {

	public int minimumLengthEncoding(String[] words) {
		int ans = 0;
		Node root = new Node();
		for (String word : words) {
			ans += root.add(word);
		}
		return ans;
	}

	class Node {

		Node[] me = new Node[26];
		int len;

		public int add(String word) {
			Node node = this;
			char[] cs = word.toCharArray();
			int isNew = 0, add = 0, len = cs.length;
			for (int i = len - 1; i >= 0; i--) {
				int c = cs[i] - 'a';
				isNew = 0;
				if (node.me[c] == null) {
					node.me[c] = new Node();
					isNew = 1;
				} else if (node.me[c].len != 0) {
					add = node.me[c].len;
					node.me[c].len = 0;
				}
				node = node.me[c];
			}
			if (isNew == 0) {
				return 0;
			}
			node.len = len;
			return add == 0 ? len + 1 : len - add;
		}

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
